<?php
namespace Wapv2\Controller;
use Think\Controller;
use Think\Model;
/***
 * 尚美生活中秋节活动
 * 2017年9月25日
 *
 */
class MoonFestivalController extends Controller{
    private $appId = "wxa75db3ff18ee9c04";
    private $appSec = "1f6eb1a8d79c662158df86848cbfb819";
    private $comId = "40";
    /**
     * 获取粉丝欣喜
     * @param  $appId
     * @param  $appSec
     */
    public function getFsInfo(){
        if(IS_AJAX)$this->ajaxReturn("非法请求！");

        $code = $_GET['code'];
        $link = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appId."&secret=".$this->appSec."&code=".$code."&grant_type=authorization_code";
        $s = curlSend($link);
        $s = json_decode($s,true);

        if($_GET['state'] == "snsapi_userinfo"){
            $link = "https://api.weixin.qq.com/sns/userinfo?access_token=".$s['access_token']."&openid=".$s['openid']."&lang=zh_CN";
            $s = curlSend($link);
            $s = json_decode($s,true);
        }

        //=============================返回到原方法
        redirect("/Wapv2/MoonFestival/activeIndex/?openid=".$s["openid"]);
    }
    /**
     * 活动首页
     */
    public function activeIndex(){
        if(IS_AJAX)$this->ajaxReturn("非法请求！");
        if($_SERVER['REQUEST_TIME'] < strtotime(date("2017-09-29"))){
            header("Content-type:text/html;charset=utf-8");
            echo "活动尚未开始...！";
            exit();
        }
        if($_SERVER['REQUEST_TIME'] > strtotime(date("2017-10-09"))){
            header("Content-type:text/html;charset=utf-8");
            echo "活动结束咯...！";
            exit();
        }
        $openId = htmlspecialchars(I("get.openid",""),ENT_QUOTES);
//    $openId = htmlspecialchars(I("get.openid","oGbS-tz4tqGWjYXrX-mQ6gA9nd0M"),ENT_QUOTES);

        if(empty($openId)){
            $domain = "123".$_SERVER['HTTP_HOST'];
            $domain = str_replace("123www.", "", $domain);
            $domain = str_replace("123", "", $domain);

            $redir = "http://www.".$domain."/Wapv2/MoonFestival/getFsInfo";
            redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appId."&redirect_uri=".urlencode($redir)."&response_type=code&scope=snsapi_userinfo&state=snsapi_userinfo#wechat_redirect");
        }

        session("openId",$openId);

        $model = new Model();
        $isHas =$model->table("wx_moon_nums")->where("openId = '".$openId."' AND TO_DAYS(dates)=TO_DAYS(NOW())")->count("id");
        if(!intval($isHas)){
            $arus = array();
            $arus['openId'] = $openId;
            $arus['nums'] = 0;
            $arus['status'] = 0;//表示可以答题
            $arus['dates'] = date("Y-m-d H:i:s");
            $model->table("wx_moon_nums")->add($arus);
            unset($arus);
        }

        //分享代码配置参数
        $a = get_js_sdk($this->appId,$this->appSec);
        $this->assign("confinfo",$a);

        $this->assign("openId",$openId);
        $this->display("Default/moon_index");
    }
    /**
     * 点击开始烧脑后判断答题次数
     */
    public function isChance(){
        if(IS_AJAX && IS_POST){
            //查看当天还有几次答题机会
            $openId = htmlspecialchars(I('post.openId',''),ENT_QUOTES);
            file_put_contents("moon_chance.txt", "====".$openId."==".date("Y-m-d H:i:s")."\r\n",FILE_APPEND);
            $model = new Model();
            $mynums = $model->table("wx_moon_nums")->where("openId = '".$openId."'  AND TO_DAYS(dates)=TO_DAYS(NOW()) AND status=0")->field("nums")->find();
            file_put_contents("moon_chance.txt", "===aa===".$mynums['nums']."==".date("Y-m-d H:i:s")."\r\n",FILE_APPEND);
            if($mynums && (intval($mynums['nums'])>=0 && intval($mynums['nums'])<10)){//若是当天没有参与过并且不多余10次的话就可以继续答题
                $aru = array();
                $aru['errCode']=1;
                $aru['errMsg']="继续答题";
                $this->ajaxReturn($aru);
            }else{//若是当天答题次数等于10次
                $aru = array();
                $aru['errCode']=2;
                $aru['errMsg']="当天答题机会已用完!";
                $this->ajaxReturn($aru);
            }
        }else {
            $this->ajaxReturn("非法请求！");
        }
    }
    /**
     * 开始答题后开始更新记录答题次数表
     */
    public function updateNums(){
        $openId = htmlspecialchars(I('post.openId',''),ENT_QUOTES);
        $model = new Model();
        $nownums = $model->table("wx_moon_nums")->where("openId = '".$openId."'  AND TO_DAYS(dates)=TO_DAYS(NOW())")->field("nums")->find();
        $arus = array();
        $arus['status'] = 1;//表示已参与
        $arus['nums'] = $nownums['nums']+1;
        $model->table("wx_moon_nums")->where("openId = '".$openId."'  AND TO_DAYS(dates)=TO_DAYS(NOW())")->save($arus);
        unset($arus);
    }
    /**
     * 分享后更新答题次数
     */
    public function shareNums(){
        $openId = htmlspecialchars(I('get.openId',''),ENT_QUOTES);
        $model = new Model();
        $nownums = $model->table("wx_moon_nums")->where("openId = '".$openId."'  AND TO_DAYS(dates)=TO_DAYS(NOW())")->field("nums")->find();
        $arus = array();
        $arus['status'] = 0;
        $model->table("wx_moon_nums")->where("openId = '".$openId."'  AND TO_DAYS(dates)=TO_DAYS(NOW())")->save($arus);
        unset($arus);
    }
    /**
     * 抽奖页面
     */
    public function prize(){
        $openId = htmlspecialchars(I('get.openId',''),ENT_QUOTES);
        if(session("openId")!=$openId){
            echo "非法请求";
            die;
        }else{
            $this->assign("openId",$openId);
            $this->display("Default/moon_prize");
        }
    }
    /**
     * 点击指针开始抽奖
     */
    public function startPrize(){
        if(!IS_AJAX || !IS_POST) $this->ajaxReturn(array('errMsg'=>'非法请求!','errCode'=>'fail'));
        $openId = htmlspecialchars(I('post.openId'),ENT_QUOTES);
        $model = new Model();
        $row   = $model->table("wx_compass")->field("prize")->where("id = '".$this->comId."'")->find();
        $prize = unserialize($row['prize']);
        $this->getPrize($prize, $this->comId,$openId);
    }
    /**
     * 保存中奖用户的信息
     */
    public function saveUser(){
        if(IS_AJAX && IS_POST){
            //更新中奖用户的信息
            $model = new Model();
            $info = array();
            $info['name'] = htmlspecialchars(I('post.name',''),ENT_QUOTES);
            $info['mobile'] = htmlspecialchars(I('post.mobile',''),ENT_QUOTES);
            $info['address'] =htmlspecialchars(I('post.address',''),ENT_QUOTES);
            $arg = array();
            $arg["uInfo"] = serialize($info);

            $res = $model->table("wx_cprize")->where("id=".session('myGiftId'))->save($arg);
            if($res!==false || 0!==$res){
                $this->ajaxReturn(array("errMsg"=>"保存成功","errCode"=>"1"));
            }else{
                $this->ajaxReturn(array("errMsg"=>"保存失败","errCode"=>"0"));
            }

        }else{
            $this->ajaxReturn(array("errMsg"=>"非法请求"));
        }
    }
    /**
     * 前台微信抽奖
     * total：奖品总数量
     * perDay：每天被抽中的最大个数
     * min：奖品位置最小角度
     * max：奖品位置最大角度
     * v：奖品被抽中的概率
     */
    public function getPrize($prize,$comId,$openId){
        //配置奖品在大转盘显示的位置
        foreach($prize as $key => $value){//6格
            switch ($key){
                case 0:
                    $prize[$key]['min']=0;
                    $prize[$key]['max']=29;
                    break;
                case 1:
                    $prize[$key]['min']=30;
                    $prize[$key]['max']=89;
                    break;
                case 2:
                    $prize[$key]['min']=90;
                    $prize[$key]['max']=149;
                    break;
                case 3:
                    $prize[$key]['min']=150;
                    $prize[$key]['max']=209;
                    break;
                case 4:
                    $prize[$key]['min']=210;
                    $prize[$key]['max']=269;
                    break;
                case 5:
                    $prize[$key]['min']=270;
                    $prize[$key]['max']=330;
                    break;
                case 6:
                    $prize[$key]['min']=331;
                    $prize[$key]['max']=360;
                    break;
            }
        }

        //根据概率获取奖品及指针位置
        $proArr = array();
        foreach($prize as $key => $value){
            $proArr[$key] = $value['pro'];
        }
        $prizeId = $this->get_rand($proArr);

        $gifts = array();
        $gifts = $prize[$prizeId];
        $gifts['min'] = mt_rand($gifts['min']+7, $gifts['max']-7);
        $perDay = $gifts['perDay'];
        $totals = $gifts['total'];

        $model = new Model();

        //奖品抽中总数
        $rows = $model->table("wx_cprize")->where("prize = '".$gifts['prize']."' AND comId = '".$this->comId."'")->count("id");
        $rows = intval($rows)+1;
        if($rows > intval($totals)){
            unset($prize[$prizeId]);
            $this->getPrize($prize, $comId,$openId);
            exit();
        }

        //限制每天被抽中的上限
        $todays = $model->table("wx_cprize")
            ->where("prize = '".$gifts['prize']."' AND comId = '".$this->comId."' AND TO_DAYS(dates)=TO_DAYS(NOW())")->count("id");
        $todays = intval($todays)+1;
        if($perDay != "" && $todays > intval($perDay)){
            unset($prize[$prizeId]);
            $this->getPrize($prize, $comId,$openId);
            exit();
        }

        //保存中奖结果
        $argu = array();
        $argu['comId'] = $this->comId;
        $argu['openId'] = $openId;
        $argu['gifts'] = $gifts['name'];
        $argu['prize'] = $gifts['prize'];
        $argu['dates'] =  date("Y-m-d H:i:s");
        $argu['status'] = 1;
        $id =$model->table("wx_cprize")->add($argu);
        session("myGiftId",$id);
        //根据name值，返回不同的值
        switch ($gifts['name']){
            case "一等奖":
                $gifts['k'] = 0;
                break;
            case "二等奖":
                $gifts['k'] = 1;
                break;
            case "三等奖":
                $gifts['k'] = 2;
                break;
            case "四等奖":
                $gifts['k'] = 3;
                break;
            case "五等奖":
                $gifts['k'] = 4;
                break;
            case "六等奖":
                $gifts['k'] = 5;
                break;
        }
        unset($argu);
        //供前端大转盘展示
        file_put_contents("moon_prize.txt", "====".serialize($gifts)."==".date("Y-m-d H:i:s")."\r\n",FILE_APPEND);
        $this->ajaxReturn($gifts);
    }
    /**
     * 根据概率获取奖品ID
     * @param unknown $proArr
     * @return Ambigous <string, unknown>
     */
    function get_rand($proArr){
        $result = "";
        $proSum = array_sum($proArr);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        if($result=="")$this->get_rand($proArr);
        unset ($proArr);
        return $result;
    }
    /**
     * 查看是否分享成功
     */
    public function test(){
        $model = new Model();
        $result = $model->table("wx_moon_nums")->select();
        dump($result);
    }
}
